package com.augmentum.oes.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.augmentum.oes.Constants;
import com.augmentum.oes.model.User;
import com.augmentum.oes.service.UserService;
import com.augmentum.oes.util.SessionUtil;
import com.augmentum.oes.util.StringUtil;

@Controller
@RequestMapping("/user")
public class UserController extends ExceptionHandle {
    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public String login() {
        if (SessionUtil.getSession("user") != null) {
            return Constants.QUERYQ_PAGE;
        } else {
            return Constants.LOGIN_PAGE;
        }
    }

    @RequestMapping(value = "/saveLogin")
    public String saveLogin(User user, String go, String remember, HttpServletResponse response)
            throws RuntimeException, UnsupportedEncodingException {
        String userName = user.getUserName();
        String password = user.getPassword();
        if ("1".equals(remember)) {
            if (!StringUtil.isEmpty(userName) && !StringUtil.isEmpty(password)) {
                Cookie cookie = new Cookie("userName", URLEncoder.encode(userName, "utf-8"));
                Cookie cookie2 = new Cookie("password", URLEncoder.encode(password, "utf-8"));
                response.addCookie(cookie);
                response.addCookie(cookie2);
            }
        }
        User userChecked = userService.login(userName, password);
        user.setPassword(null);
        SessionUtil.addSession(Constants.USER, userChecked);
        if (!StringUtil.isEmpty(go)) {
            String goUrl = go.replace("#", "?");
            return "redirect:" + goUrl;
        } else {
            return Constants.QUERYQ_PAGE;
        }
    }

    @RequestMapping("/logout")
    public String logout() {
        SessionUtil.invalidate();
        return Constants.LOGIN_ACTION;
    }
    /*
     * @RequestMapping("/changeLan") public String changeLanguage(String lan,
     * HttpSession session) { if (!StringUtil.isEmpty(lan)) { User user = (User)
     * session.getAttribute("user"); if (user == null) { return
     * "redirect:/user/login"; } user.setLanguage(Integer.parseInt(lan));
     * session.setAttribute("user", user); return "redirect:/question/query"; }
     * else { return "redirect:/user/login"; } }
     */
}
